import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:meco/common/index.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class OfficialController extends GetxController {
  OfficialController();

  // 仓库
  final BrowseRecordRepository _browseRecordRepository =
      BrowseRecordRepository();
  final CommentRepository _commentRepository = CommentRepository(
    Get.find<DatabaseService>(),
  );
  final OfficialContentRepository _officialContentRepository =
      OfficialContentRepository();

  // 评论文本控制器
  late TextEditingController commentController;

  // 接收的官方内容数据
  final Rx<OfficialContent?> content = Rx<OfficialContent?>(null);

  // 拖拽比例（0.0-1.0之间）
  final RxDouble dragRatio = 0.5.obs; // 初始值设为0.5

  // 浏览用户列表
  final RxList<User> viewedUsers = <User>[].obs;
  final RxBool isLoadingUsers = false.obs;

  // 评论列表
  final RxList<CommentModel> comments = <CommentModel>[].obs;
  final RxBool isLoadingComments = false.obs;

  // 更新拖拽比例
  void updateDragRatio(double ratio) {
    dragRatio.value = ratio;
  }

  // 记录浏览
  void _recordBrowse() {
    if (content.value?.id == null) return;

    // 检查用户是否登录
    final UserService userService = Get.find<UserService>();
    if (!userService.isLoggedIn.value) return;

    // 用户已登录，记录浏览
    _browseRecordRepository.addBrowseRecord(
      BrowseRecord(
        userId: userService.currentUser.value!.id!,
        contentId: content.value!.id!,
        type: BrowseType.officialContent,
        browseTime: DateTime.now(),
      ),
    );
  }

  // 获取浏览过此内容的用户
  Future<void> loadViewedUsers() async {
    if (content.value?.id == null) return;

    isLoadingUsers.value = true;
    try {
      final users = await _browseRecordRepository.getViewedUsersByContent(
        content.value!.id!,
        BrowseType.officialContent,
      );

      viewedUsers.value = users;
    } catch (e) {
      print('获取浏览用户失败: $e');
    } finally {
      isLoadingUsers.value = false;
    }
  }

  // 获取评论列表
  Future<void> loadComments() async {
    if (content.value?.id == null) return;

    isLoadingComments.value = true;
    try {
      final contentComments = await _commentRepository.getCommentsForContent(
        content.value!.id.toString(),
        CommentType.officialContent,
      );

      comments.value = contentComments;
    } catch (e) {
      print('获取评论失败: $e');
    } finally {
      isLoadingComments.value = false;
    }
  }

  // 添加评论
  Future<void> addComment() async {
    if (content.value?.id == null || commentController.text.trim().isEmpty)
      return;

    final UserService userService = Get.find<UserService>();

    userService.checkLoginThenExecute(
      loginRequiredMessage: 'You need to login to post a comment',
      onLoggedIn: () async {
        final currentUser = userService.currentUser.value!;
        final commentText = commentController.text.trim();

        try {
          final newComment = CommentModel(
            id: '', // 由仓库生成UUID
            content: commentText,
            userId: currentUser.id.toString(),
            userName: currentUser.nickname ?? currentUser.username,
            userAvatar: currentUser.avatar ?? '',
            contentId: content.value!.id.toString(),
            type: CommentType.officialContent,
            createdAt: DateTime.now(),
          );

          await _commentRepository.addComment(newComment);
          commentController.clear(); // 清空输入框
          await loadComments(); // 重新加载评论
        } catch (e) {
          print('Adding comment failed: $e');
        }
      },
    );
  }

  // 状态更新
  _initData() {
    // 从路由参数中获取传递的内容
    if (Get.arguments != null && Get.arguments is OfficialContent) {
      content.value = Get.arguments as OfficialContent;

      // 记录浏览
      _recordBrowse();

      // 加载浏览用户
      loadViewedUsers();

      // 加载评论
      loadComments();
    }
    update(["official"]);
  }

  void onTap() {}

  @override
  void onInit() {
    super.onInit();
    commentController = TextEditingController();
  }

  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  @override
  void onClose() {
    commentController.dispose();
    super.onClose();
  }

  // 举报官方内容
  void reportOfficialContent() {
    if (content.value == null) return;

    final OfficialContent officialContent = content.value!;

    ReportBottomSheet.show(
      onReport: (reason) async {
        // 这里可以实现实际的举报逻辑，如发送到服务器
        print('举报官方内容: ${officialContent.id}, 原因: ${reason.toString()}');

        // 模拟API调用
        await Future.delayed(Duration(seconds: 1));

        // 删除官方内容
        try {
          if (officialContent.id != null) {
            // 使用Repository删除官方内容，这将通知所有观察者
            final success = await _officialContentRepository
                .deleteOfficialContent(officialContent.id!);

            if (success) {
              // 显示成功提示
              EasyLoading.showSuccess('你将不会再看到此内容');

              // 返回上一页
              Future.delayed(Duration(seconds: 1), () {
                Get.back();
              });
            } else {
              EasyLoading.showError('举报失败，请稍后再试');
            }
          }
        } catch (e) {
          print('删除官方内容失败: $e');
          EasyLoading.showError('举报失败，请稍后再试');
        }

        return true;
      },
    );
  }

  // 举报评论
  void reportComment(CommentModel comment) {
    ReportBottomSheet.show(
      onReport: (reason) async {
        // 这里可以实现实际的举报逻辑，如发送到服务器
        print('举报评论: ${comment.id}, 原因: ${reason.toString()}');

        // 模拟API调用
        await Future.delayed(Duration(seconds: 1));

        // 删除评论
        try {
          await _commentRepository.deleteComment(comment.id);

          // 显示成功提示
          EasyLoading.showSuccess('Comment has been removed');

          // 重新加载评论
          await loadComments();
        } catch (e) {
          print('删除评论失败: $e');
        }

        return true;
      },
    );
  }
}
